'use strict';
var ksrBusinessAcct = angular.module('ksrBusinessAcct',[
    'ngCookies'
    ,'ngRoute'
    ,'ui.bootstrap'
    ,'remoteValidation'
    ,'ksrBusinessAcctControllers'
    ,'ksr.filters'
    ,'ksr.services'
    ,'ksr.directives'
    ,'ksrFileupload'
    //,'KSR.filters'
    //'KSR.services'
]);

ksrBusinessAcct.config(['$routeProvider','$locationProvider',
    function($routeProvider,$locationProvider){
		$routeProvider.
		when("/overview",{
			templateUrl:'/ksr/partials/business/account-overview.htm'
			,controller:"acctOverviewCtrl"
		}).
		when("/edit-business-profile",{
			templateUrl:'/ksr/partials/business/business-profile.htm'
				,controller:"businessProfileCtrl"
		}).
		when("/change-password",{
			templateUrl:'/ksr/partials/change-password.htm'
			,controller:"changePasswordCtrl"
		}).
		when("/manage-office",{
			templateUrl:'/ksr/partials/business/manage-office.htm'
				,controller:"manageOfficeCtrl"
		}).
		when("/office/new",{
			templateUrl:'/ksr/partials/business/office.htm'
				,controller:"officeCtrl"
		}).
		when("/office/:officeId",{
			templateUrl:'/ksr/partials/business/office.htm'
			,controller:"officeCtrl"
		}).
		when("/office-photos/:id",{
			templateUrl:'/ksr/partials/fileupload.htm'
			,controller:"officePhotoCtrl"
		}).
		when("/office-reviews/:id",{
			templateUrl:'/ksr/partials/business/reviews.htm'
			,controller:"officeReviewCtrl"
		}).
		when("/events-overview",{
			templateUrl:'/ksr/partials/business/events-overview.htm'
			,controller:"eventsOverviewCtrl"
		}).
		when("/add-business-event/new",{
			templateUrl:'/ksr/partials/business/event.htm'
				,controller:"eventCtrl"
		}).
		when("/manage-business-event/:eventId",{
			templateUrl:'/ksr/partials/business/event-manage.htm'
				,controller:"manageEventCtrl"
		}).
		when("/manage-business-event/:eventId/edit-event",{
			templateUrl:'/ksr/partials/business/event.htm'
				,controller:"eventCtrl"
		}).
		when("/manage-business-event/:eventId/add-event-schedule",{
			templateUrl:'/ksr/partials/business/event-schedule.htm'
				,controller:"eventScheduleCtrl"
		}).
		when("/manage-business-event/:eventId/edit-event-schedule/:scheduleId",{
			templateUrl:'/ksr/partials/business/event-schedule.htm'
				,controller:"eventScheduleCtrl"
		}).
	
		when("/manage-business-event/:eventId/event-photos",{
			templateUrl:'/ksr/partials/fileupload.htm'
			,controller:"eventPhotoCtrl"
		}).
		otherwise({
			redirectTo:'/overview'
		});
	}
]);

/*controllers*/
var ksrBusinessAcctControllers = angular.module("ksrBusinessAcctControllers",[]);

ksrBusinessAcctControllers.controller('acctOverviewCtrl', ['$scope',
	 function($scope) {
	   console.log("acctOverviewCtrl");
	   $scope.breadcrumbs=[
	                  	{"name":"Account","url":"#/overview"}
	                  	,{"name":"overview","url":""}
	                ];
 }]);

ksrBusinessAcctControllers.controller('businessProfileCtrl', ['$scope', '$location','$window','ksrCacheSvc','jsonSvc',
    function($scope, $location,$window,ksrCacheSvc,jsonSvc) {
	console.log("businessProfileCtrl");
	
	    ksrCacheSvc.get("business",true).then(function(data){
	    	if (data.id){ 
				$scope.title = "Edit business profile";
				$scope.mode="edit";
				$scope.breadcrumbs=[{"name":"Account settings","url":"#/overview"},{"name":"profile","url":""}];
	    		$scope.business = data;
	    	} else {
	    		$scope.title = "Create your business profile";
				$scope.mode="create";
				$scope.business = {categories:[]};
	    	}
	    	
	    },function(err){

	    })  ; 

	
	$scope.submit = function(){
		jsonSvc.saveItem({entityType:"business",type:"profile"},$scope.business).$promise.then(function(data){
			console.log("udpate business status:"+data.status);
			if ($scope.mode==="edit"){
				$location.path("#/overview");
			} else {
				$window.location.href="/ksr/business/profile.html";
			}
		});
	}
	
}]);
ksrBusinessAcctControllers.controller('changePasswordCtrl', ['$scope', '$location','jsonSvc',
                                                             function($scope,$location,jsonSvc) {
	console.log("changePasswordCtrl");
	$scope.breadcrumbs=[
	                    {"name":"Account","url":"#/overview"}
	                    ,{"name":"password","url":""}
	                    ];
	$scope.pwdObj = {}
	$scope.submit = function(){
		jsonSvc.changePassword({entityType:"business"},$scope.pwdObj).$promise.then(function(data){
			if (data.status === "ok"){
				console.log("udpate password successfully");
				$location.path("#/overview");
			} else {
				$scope.errMsg = data.status;
			}
		});
	}	
	
}]);

ksrBusinessAcctControllers.controller('manageOfficeCtrl', ['$scope','$rootScope','$modal','$timeout','$sce','ksrCacheSvc','jsonSvc',
	 function($scope,$rootScope,$modal,$timeout,$sce,ksrCacheSvc,jsonSvc) {
	   console.log("acctOverviewCtrl");
	   $scope.breadcrumbs=[
	                  	{"name":"Account","url":"#/overview"}
	                  	,{"name":"Manage Offices","url":""}
	                ];
	    $scope.alerts = [];
	    $scope.closeAlert = function(index) {
		    $scope.alerts.splice(index, 1);
		  };
	    

	    ksrCacheSvc.get("business",false).then(function(data){
	    	$scope.business = data;
	    })	


	    ksrCacheSvc.get("officeList",false).then(function(data){
	    	  
			    

	    	$scope.offices = data;
		   angular.forEach($scope.offices, function(office){
		   		ksrCacheSvc.get("officeReviewList",false,{id:office.id,rating:0}).then(function(data){
		    		office.reviewList = data;
		    		office.reviewNumbers=data.rating100.length+","+data.rating80.length+","+data.rating60.length+","+data.rating40.length+","+data.rating20.length;
		    		office.reviewCount=data.rating100.length+data.rating80.length+data.rating60.length+data.rating40.length+data.rating20.length;
		    		console.log("success to retrieve the reviewList for office:"+office.id);		   			
		   		},function(err){
		   			console.error("fail to retrieve the reviewList  for office:"+office.id);
		   		})
		   })
	    })
	    ksrCacheSvc.get("baseUrl",true).then(function(data){
	    	$scope.baseUrl = data.baseUrl;
	    })
	    $scope.deleteOffice=function(id){
	         // $modal.open();
	     var modalInstance = $modal.open({templateUrl: '/ksr/partials/confirmModal.htm'});

	    $rootScope.itemName = "the office";
	    $rootScope.yes = function () {
	        modalInstance.close("yes");
	    };
	    $rootScope.no = function () {
	        modalInstance.dismiss('cancel');
	    };

	    modalInstance.result.then(function () {
			if (id>=0){
				console.log("delete office,id="+id);
				jsonSvc.removeItem({entityType:"business",type:"office",eid:id,action:"remove"}).$promise.then(function(data){
					if (data.status==="success"){
						console.log("remove office successfully");
						var alert ={
							type:"success",
							msg: $sce.trustAsHtml('<span class="glyphicon glyphicon-ok-circle"> </span> remove office successfully')
						};
						$scope.alerts.push(alert);
						$timeout(
                            function() {
                                $scope.closeAlert($scope.alerts.indexOf(alert));
                            }, 3000);
						//remove it from office list so that don't need to refresh page
						var deletedIdx = -1;
						angular.forEach($scope.offices, function(office,idx){
							if (id===office.id){
								deletedIdx=idx; 
							}
						})
						if (deletedIdx>=0){
							$scope.offices.splice(deletedIdx,1);
						}
					} else {
						console.error("remove office failed! Error:"+data.error);
						$scope.alerts.push({type:'danger', msg:$sce.trustAsHtml('Fail to remove the office! Please try again later!')});
					}
				});
			}
	    }, function () {
	      console.log('user cancel the delete action! id='+id);
	    });  
	    }
	  
 }]);

ksrBusinessAcctControllers.controller('officeCtrl', ['$scope', '$routeParams','$location','jsonSvc','ksrCacheSvc',
    function($scope,$routeParams,$location,jsonSvc,ksrCacheSvc) {
	console.log("officeCtrl");
	$scope.breadcrumbs=[
	                    {"name":"Account","url":"#/overview"}
	                  	,{"name":"Manage Offices","url":"#/manage-office"}
	                    ,{"name":"office","url":""}
	                    ];

	   if ($routeParams.officeId){
		   console.log("editoffice="+$routeParams.officeId);

		   ksrCacheSvc.getItemById($routeParams.officeId,"officeList",true).then(function(data){
		   		$scope.office = data;
		   		$scope.mode="edit";	
		   })
		   // $scope.office = ksrCacheService.getOfficeById(parseInt($routeParams.officeId));
	   } else {
		   console.log("new office");
		   $scope.office = {};
		   ksrCacheSvc.get("business",true).then(function(data){
	    		$scope.office.business = data;
	    	})	  
		   $scope.mode="new";
	   }

    
	$scope.submit = function(){
		jsonSvc.saveItem({entityType:"business",type:"office"},$scope.office).$promise.then(function(data){
				console.log("office status:"+data.status);
				$location.path("#/overview");			
		},function(err){});

	}
	
}]);
ksrBusinessAcctControllers.controller('officePhotoCtrl', ['$scope','$controller', '$http','$routeParams',
                                                     function($scope, $controller,$http,$routeParams) {
	console.log("officeCtrl");
	$scope.breadcrumbs=[
	                    {"name":"Account","url":"#/overview"}
	                  	,{"name":"Manage Offices","url":"#/manage-office"}
	                    ,{"name":"add or remove photos","url":""}
	                    ];
    $controller("ksrFileUploadController", {
        $scope: $scope,
        $http:$http,
        $routeParams:$routeParams
    });
	
}]);

ksrBusinessAcctControllers.controller('officeReviewCtrl', ['$scope','$routeParams','ksrCacheSvc',
	 function($scope, $routeParams,ksrCacheSvc) {
	   console.log("acctOverviewCtrl");
	   $scope.breadcrumbs=[
	                  	{"name":"Account","url":"#/overview"}
	                  	,{"name":"Manage Offices","url":"#/manage-office"}
	                  	,{"name":"office reviews","url":""}
	                ];

	    	ksrCacheSvc.get("officeReviewList",false,{id:$routeParams.id}).then(function(data){
		    		$scope.reviewList = data;
		    		console.log("success to retrieve the reviewList for office:"+$routeParams.id);		   			
		   		},function(err){
		   			console.error("fail to retrieve the reviewList  for office:"+$routeParams.id);
		   		})
	  
 }]);
